//http://www.cnblogs.com/mycoding/archive/2011/07/07/2099878.html
//http://www.cnblogs.com/Gavinzhao/archive/2010/12/27/2549996.html
var MyGrid = {
    GridCurrentId : null,
    GridTempResult : [true, ''],
    Instance : null,
    defaultSettings :{
        gridItemName : "#grid-table",
        pager : "#grid-pager",
        datatype: "json",
        height: 450,
        viewrecords : true,
        rowNum:10,
        rowList:[10,20,30],
        altRows: true,
        //toppager: true,
        multiselect: true,
        //multikey: "ctrlKey",
        multiboxonly: true,
        loadComplete : function() {
            var table = this;
            setTimeout(function(){
                MyGrid.styleCheckbox(table);
                MyGrid.updateActionIcons(table);
                MyGrid.updatePagerIcons(table);
                MyGrid.enableTooltips(table);
            }, 0);
        },
        caption: "",//title
        autowidth: true,
        prmNames: {
            id:"id", // 表示当在编辑数据模块中发送数据时，使用的id的名称
            oper:"oper", // operation参数名称
            editoper:"edit", // 当在edit模式中提交数据时，操作的名称
            addoper:"add", // 当在add模式中提交数据时，操作的名称
            deloper:"del" // 当在delete模式中提交数据时，操作的名称
        }
    },
    dialogSettings : {
        center : function()
        {
            //center dialog start
            var dlgDiv = $('.ui-jqdialog');
            var dlgWidth = dlgDiv.width();
            var dlgHeight = dlgDiv.height();
            var parentDiv = $('body');
            var parentWidth = parentDiv.width();
            var parentHeight = parentDiv.height();
            dlgDiv[0].style.top = Math.round((parentHeight-dlgHeight)/2) + "px";
            dlgDiv[0].style.left = Math.round((parentWidth-dlgWidth)/2) + "px";
            //center dialog end
        }
    },
    //switch element when editing inline
    aceSwitch : function ( cellvalue, options, cell ) {
        setTimeout(function(){
            $(cell) .find('input[type=checkbox]')
                .wrap('<label class="inline" />')
                .addClass('ace ace-switch ace-switch-5')
                .after('<span class="lbl"></span>');
        }, 0);
    },
    //enable date picker
    pickDate : function ( cellvalue, options, cell ) {
        setTimeout(function(){
            $(cell) .find('input.datepicker')
                .datepicker({format:'yyyy-mm-dd' , autoclose:true});
        }, 0);
    },
    style_edit_form : function(form) {
        MyGrid.dialogSettings.center();
        //enable date picker on "sdate" field and switches for "stock" field
        form.find('input.datepicker')
            .datepicker({format:'yyyy-mm-dd' , autoclose:true})
            .end().find('input[name=stock]')
            .addClass('ace ace-switch ace-switch-5')
            .wrap('<label class="inline" />')
            .after('<span class="lbl"></span>');

        //update buttons classes
        var buttons = form.next().find('.EditButton .fm-button');
        buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//ui-icon, s-icon
        buttons.eq(0).addClass('btn-primary').prepend('<i class="icon-ok"></i>');
        buttons.eq(1).prepend('<i class="icon-remove"></i>');

        buttons = form.next().find('.navButton a');
        buttons.find('.ui-icon').remove();
        buttons.eq(0).append('<i class="icon-chevron-left"></i>');
        buttons.eq(1).append('<i class="icon-chevron-right"></i>');
    },
    style_delete_form : function (form) {
        MyGrid.dialogSettings.center();
        var buttons = form.next().find('.EditButton .fm-button');
        buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//ui-icon, s-icon
        buttons.eq(0).addClass('btn-danger').prepend('<i class="icon-trash"></i>');
        buttons.eq(1).prepend('<i class="icon-remove"></i>')
    },
    style_search_filters : function (form) {
        MyGrid.dialogSettings.center();
        form.find('.delete-rule').val('X');
        form.find('.add-rule').addClass('btn btn-xs btn-primary');
        form.find('.add-group').addClass('btn btn-xs btn-success');
        form.find('.delete-group').addClass('btn btn-xs btn-danger');
    },
    style_search_form : function (form) {
        MyGrid.dialogSettings.center();
        var dialog = form.closest('.ui-jqdialog');
        var buttons = dialog.find('.EditTable');
        buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'icon-retweet');
        buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'icon-comment-alt');
        buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'icon-search');
    },
    beforeDeleteCallback : function (e) {
        var form = $(e[0]);
        if(form.data('styled')) return false;

        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
        MyGrid.style_delete_form(form);
        form.data('styled', true);
    },
    beforeEditCallback : function (e) {
        var form = $(e[0]);
        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
        MyGrid.style_edit_form(form);
    },
    //it causes some flicker when reloading or navigating grid
    //it may be possible to have some custom formatter to do this as the grid is being created to prevent this
    //or go back to default browser checkbox styles for the grid
    styleCheckbox : function (table) {
        /**
         $(table).find('input:checkbox').addClass('ace')
         .wrap('<label />')
         .after('<span class="lbl align-top" />')


         $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
         .find('input.cbox[type=checkbox]').addClass('ace')
         .wrap('<label />').after('<span class="lbl align-top" />');
         */
    },
    //unlike navButtons icons, action icons in rows seem to be hard-coded
    //you can change them like this in here if you want
    updateActionIcons : function (table) {

    },
    //replace icons with FontAwesome icons like above
    updatePagerIcons : function (table) {
        var replacement =
        {
            'ui-icon-seek-first' : 'icon-double-angle-left bigger-140',
            'ui-icon-seek-prev' : 'icon-angle-left bigger-140',
            'ui-icon-seek-next' : 'icon-angle-right bigger-140',
            'ui-icon-seek-end' : 'icon-double-angle-right bigger-140'
        };
        $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
            var icon = $(this);
            var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
            if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
        })
    },
    enableTooltips : function (table) {
        $('.navtable .ui-pg-button').tooltip({container:'body'});
        $(table).find('.ui-pg-div').tooltip({container:'body'});
    },
    createGrid : function(settings)
    {
        // Merge object2 into object1
        jQuery.extend( MyGrid.defaultSettings, settings );
        var grid_selector = MyGrid.defaultSettings.gridItemName;
        var pager_selector = MyGrid.defaultSettings.pager;

        jQuery(grid_selector).jqGrid(MyGrid.defaultSettings);

        //navButtons
        jQuery(grid_selector).jqGrid(
            'navGrid',
            pager_selector,
            {
                //navbar options
                edit: true,
                editicon : 'icon-pencil blue',
                add: true,
                addicon : 'icon-plus-sign purple',
                del: true,
                delicon : 'icon-trash red',
                search: true,
                searchicon : 'icon-search orange',
                refresh: true,
                refreshicon : 'icon-refresh green',
                view: true,
                viewicon : 'icon-zoom-in grey'
            },
            {
                //edit record form
                //closeAfterEdit: true,
                editCaption : "编辑",
                recreateForm: true,
                beforeShowForm : function(e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
                    MyGrid.style_edit_form(form);
                },
                beforeSubmit : function(e)
                {
                    return MyGrid.validator(e);
                },
                afterSubmit : function(response, postdata) {
                    var result = JSON.parse(response.responseText);
                    if(result.status=='fail')
                    {
                        return [false, result.message] ;
                    }
                    else
                    {
                        return [true, result.message] ;
                    }
                }
            },
            {
                //new record form
                addCaption : "添加",
                modal: false, //模态显示
                drag: true,  //窗体是否可以拖动
                closeAfterAdd: true,
                recreateForm: true,
                viewPagerButtons: false,
                beforeShowForm : function(e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                    MyGrid.style_edit_form(form);
                },
                beforeSubmit : function(e)
                {
                    return MyGrid.validator(e);
                },
                afterSubmit : function(response, postdata) {
                    var result = JSON.parse(response.responseText);
                    if(result.status=='fail')
                    {
                        return [false, result.message] ;
                    }
                    else
                    {
                        return [true, result.message] ;
                    }
                }
            },
            {
                //delete record form
                recreateForm: true,
                beforeShowForm : function(e) {
                    var form = $(e[0]);
                    if(form.data('styled')) return false;

                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
                    MyGrid.style_delete_form(form);

                    form.data('styled', true);
                }
            },
            {
                //search form
                recreateForm: true,
                afterShowSearch: function(e){
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />');
                    MyGrid.style_search_form(form);
                },
                afterRedraw: function(){
                    MyGrid.style_search_filters($(this));
                }
                ,
                multipleSearch: true
                /**
                 multipleGroup:true,
                 showQuery: true
                 */
            },
            {
                //view record form
                recreateForm: true,
                beforeShowForm: function(e){
                    MyGrid.dialogSettings.center();
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                }
            }
        );
        MyGrid.Instance = jQuery(grid_selector);
    },
    exists : function(url, params)
    {
        //var row = jQuery(MyGrid.defaultSettings.gridItemName).jqGrid('getRowData',id);
        $.ajax({
            url : url,
            type : 'GET',
            dataType : 'json',
            async: false,
            data: params ,
            complete : function(jqXHR) {
                var responseData = JSON.parse(jqXHR.responseText);
                if(responseData.status=='success')
                {
                    MyGrid.GridTempResult = [false, responseData.message] ;
                }
                else
                {
                    MyGrid.GridTempResult = [true, responseData.message] ;
                }
            }
        });
        return MyGrid.GridTempResult;
    },
    validator:function(params)
    {
        MyGrid.GridTempResult = [true, ''] ;
        $.ajax({
            url : GridSetting.validateurl,
            type : 'GET',
            dataType : 'json',
            async: false,
            data: params ,
            complete : function(jqXHR) {
                var responseData = JSON.parse(jqXHR.responseText);
                if(responseData.status=='validate')
                {
                    $.each(responseData.result, function(key, val){
                        for(var i=0; i < val.length; i++)
                        {
                            MyGrid.GridTempResult = [false, val[i]] ;
                            return;
                        }
                    });
                }
            }
        });
        return MyGrid.GridTempResult ;
    }
};